package utils

import (
	"os"

	"rdiot-demo/internal/shared/config"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

// NewLogger 创建新的日志记录器
func NewLogger(loggerConfig config.LoggerConfig) (*zap.Logger, error) {
	// 解析日志级别
	level, err := zapcore.ParseLevel(loggerConfig.Level)
	if err != nil {
		level = zapcore.InfoLevel
	}

	// 创建核心配置
	core := zapcore.NewCore(
		getEncoder(),
		getLogWriter(loggerConfig),
		level,
	)

	// 创建logger
	logger := zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))

	return logger, nil
}

// getEncoder 获取编码器
func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

// getLogWriter 获取日志写入器
func getLogWriter(config config.LoggerConfig) zapcore.WriteSyncer {
	// 文件输出
	fileWriter := &lumberjack.Logger{
		Filename:   config.Filename,
		MaxSize:    config.MaxSize,
		MaxAge:     config.MaxAge,
		MaxBackups: config.MaxBackups,
		Compress:   config.Compress,
	}

	// 同时输出到文件和控制台
	return zapcore.NewMultiWriteSyncer(
		zapcore.AddSync(fileWriter),
		zapcore.AddSync(os.Stdout),
	)
}
